import { FunctionComponent, ReactElement, useEffect } from 'react';
import { getStorage } from '../utils/storage';
import { Navigate, useLocation } from 'react-router-dom';
import { message } from 'antd';
interface RequireAuthProps {
  children: ReactElement;
}
const RequireAuth: FunctionComponent<RequireAuthProps> = ({ children }) => {
  const token = getStorage('token') || '';
  const location = useLocation();
  useEffect(() => {
    !token && message.error('请先登录');
  }, [token]);
  // 如果token存在，则渲染element组件，否则重定向到登录页面
  return token ? children : <Navigate to="/login" replace state={{ from: location }} />;
};
export default RequireAuth;
